# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, absolute_import
from math import atan2, degrees
from src import vars
from src.consts import *

def in_rect(x, y, rx, ry, rw, rh):
    """returns true if point is in the rect"""
    return True if x >= rx and x <= rx + rw and y >= ry and y <= ry + rh else False

def dir_between(ax, ay, bx, by):
    """returns direction between two field coords"""
    dx, dy = bx - ax, by - ay
    fw, fh = vars.field_w, vars.field_h
    
    # wrapping
    if (ay == 0 and by == fh-1) or (ay == fh-1 and by == 0):
        dy = -1 if ay - by < 0 else 1
    if (ax == 0 and bx == fw-1) or (ax == fw-1 and bx == 0):
        dx = -1 if ax - bx < 0 else 1
    
    if dy == 0: # horizontal
        return DIR_W if dx < 0 else DIR_E
    elif dx == 0: # vertical
        return DIR_N if dy > 0 else DIR_S
    elif dx < 0: # diagonal to west
        return DIR_NW if dx < dy else DIR_SW
    elif dx > 0: # diagonal to east
        return DIR_SE if dx > dy else DIR_NE
    else:
        raise RuntimeError

def dir_between_px(ax, ay, bx, by):
    """same as dir_between() but for pixel coords"""
    return degrees(atan2(bx - ax, by - ay)) % 360 # fixme

def field_delta(ax, ay, bx, by, fw, fh):
    """returns wrapped neg/pos delta between two field coords"""
    dx_r, dx_l = (bx - ax) % fw, -((ax - bx) % fw)
    dy_r, dy_l = (by - ay) % fh, -((ay - by) % fh)
    dx = dx_r if abs(dx_r) < abs(dx_l) else dx_l
    dy = dy_r if abs(dy_r) < abs(dy_l) else dy_l
    #print "DX, DY", dx, dy
    return (dx, dy)
    
def get_k_by_dir(dir): # fixme: fix name
    """returns field coord increment coefficient by direction (dir) for moving"""
    return (0, 1) if dir == DIR_N else (0, -1) if dir == DIR_S else (-1, 0) if dir == DIR_W \
        else (1, 0) if dir == DIR_E else (1, 1) if dir == DIR_NE else (1, -1) if dir == DIR_SE \
        else (-1, 1) if dir == DIR_NW else (-1, -1) if dir == DIR_SW else RuntimeError

def wrap(x, y):
    """wrapping world's coords"""
    return (x % vars.field_w, y % vars.field_h)

def sdir_to_deg(s):
    return globals()['DIR_%s' % s.upper()]

def deg_to_sdir(v):
    _m = {0: 'N', 90: 'E', 180: 'S', 270: 'W', 45: 'NE', 135: 'SE', 225: 'SW', 315: 'NW'}
    return _m[v]
